import { Injectable } from '@angular/core';

import { GeneralConfig } from '../config/general.config';
import { AppSetting } from '../models/app-setting.model';
import { SshConnectionConfig } from '../models/ssh-connection-config.model';

const Store = require('electron-store');

/**
 * The service manages the local saved settings.
 * 
 * It is used by multiple biz modules. That's why it's not in the app-setting.module.
 */
@Injectable()
export class AppSettingService {
    private appSettings: AppSetting;
    private store = new Store();

    constructor() { }

    /**
     * Gets saved settings. If it does not exist then creates a default one.
     */
    get settings(): AppSetting {
        // Try to load the saved settings.
        if (this.appSettings == null) {
            this.appSettings = this.store.get(GeneralConfig.appSettingStorageKey);
        }

        // If no saved settings then creates a default one.
        if (this.appSettings == null) {
            this.appSettings = new AppSetting();
            this.appSettings.remoteSetting = new SshConnectionConfig();
        }

        return this.appSettings;
    }

    /**
     * Saves current app settings.
     */
    save(): void {
        this.store.set(GeneralConfig.appSettingStorageKey, this.appSettings);
    }
}